package
{
	public class StateStack
	{
		protected var states:Vector.<State>;
		public function StateStack()
		{
			states = new Vector.<State>();
		}
		public function Push(state:State):void
		{
			state.stateIndex = GetStateCount();
			states.push(state);
			GetCurrent().Init();
		}
		public function Pop():void
		{
			GetCurrent().Release();
			delete GetCurrent();
			states.pop();
		}
		
		public function SwitchState(state:State,  popAllStates:Boolean):void
		{
			
			if (popAllStates)
			{
				for (var i:int = states.length-1; i >= 0; i--)
				{
					Pop();
				}
			}
			else
			{
				Pop();
			}
			
			Push(state);
		}
		
		public function GetCurrent():State
		{
			if(states.length == 0) return null;
			return states[states.length-1];
		}
		public function ClearAll():void
		{
			states = new Vector.<State>();
		}
		public function GetStateCount():uint
		{
			return states.length;
		}
		public function GetStateAt(index:uint):State
		{
			return states[index];
		}
		public function RemoveStateAt(index:int):void
		{
			if(index >= 0 && index < states.length)
			{
				states[index].Release();
				delete states[index];
				states.splice(index,1);
			}
			for(var i:int = index;i<states.length;i++)
			{
				states[i].stateIndex--;
			}
		}
	}
}